var $,layer,form,table,laydate,element;//定义layui模块
var addindex = 0;

layui.use(['laydate', 'table','form','layer','jquery','util','element'], function () {
    $ = layui.$,layer = layui.layer,form = layui.form,table = layui.table,laydate = layui.laydate,util = layui.util,element=layui.element;

    //console.log('detailList',detailList);
    if(detailList==null){
        detailList== [];
    }
    if(detailList!=null && detailList.length>0){
        setRowId();
    }
    //console.log('detailList111',detailList);
    // 创建渲染实例
    $.tablelist.init({
        elem: '#dhtable',//表id
        id:'dhtable',
        data:detailList,
        toolbar: '#toolbarDemo',//开启表格头部工具栏
        //height: window.innerHeight - 280, // 最大高度减去其他容器已占有的高度差
        height: '450',
        cellMinWidth: 60,//设置所有普通单元格的最小宽度
        totalRow: false, // 开启合计行，true开启，false关闭
        page: false,//开启分页
        limit:100,
        loading:false,
        skin: 'grid',//设置表格边框风格
        even: true, // 开启隔行背景
        //表头属性集
        cols: [
            [
                //{field:'checkbox',align:"center",fixed:'left',type:'checkbox'},
                {title: '<span style="color: red;">*</span>'+' 商品编码', field:'commodityCode', align:"center",width:100}
                ,{title:'<span style="color: red;">*</span>'+' 商品名称', field:'name', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 箱数', field:'numBox', align:"center",width:100,templet:
                    function(d){
                        if(enableEdit==1){
                            return '<input type="number" onchange="numberInput1(\''+d.gaugeMaintenanceId+'\',this)" oninput="if(value.length>5)value=value.slice(0,5)" placeholder="" class="layui-input" value="'+d.numBox+'">';
                        }else {
                            return '<span>'+d.numBox+'</span>';
                        }
                    }
            }
                ,{title: '<span style="color: red;">*</span>'+' 单箱数量', field:'numSingleBox', align:"center",width:100}
                ,{title: '商品数量', field:'numCommodity', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 箱规(cm)', field:'volume', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 箱重(kg)', field:'weight', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 商品品名', field:'productNameCn', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 商品材质', field:'productMaterialCn', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 海关编码', field:'productCodeHs', align:"center",width:100}
                //,{title: '所在仓库', field:'codeStockOn', align:"center",width:100,templet: '#detailRow'} oninput="if(value.length>5)value=value.slice(0,5)"
                ,{title: '<span style="color: red;">*</span>'+' 所在仓库', field:'codeStockOn', align:"center",width:100,templet:
                    function(d){
                        return '<div onclick="addRowIn(\''+d.gaugeMaintenanceId+'\')"><span style="color: red;">'+(enableEdit== 1?'+':'')+'</span> <span >'+d.codeStockOn+'</span></div>';
                    }
            }
                ,{title: '<span style="color: red;">*</span>'+' 货位编码', field:'codeStockLocation', align:"center",width:100,templet:
                    function(d){
                        if(enableEdit==1){
                            return '<span>'+d.codeStockLocation+'</span>'+
                                '<i class="layui-icon layui-icon-more hlicon" style="float: right;" onclick="getCodeStockLocation('+d.rowId+')"></i>';
                        }else {
                            return '<span>'+d.codeStockLocation+'</span>';
                        }

                    }
            }
                ,{title: '<span style="color: red;">*</span>'+' 库区', field:'codeStockArea', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 可用数量', field:'numAvailable', align:"center",width:100}
                ,{title: '<span style="color: red;">*</span>'+' 发货数量', field:'numDeliver', align:"center",width:100,templet:
                    function(d){
                        if(enableEdit==1){
                            return '<input type="number" onchange="numDeliverInput(\''+d.rowId+'\',this)" oninput="if(value.length>5)value=value.slice(0,5)" placeholder="" class="layui-input input-numDeliver" value="'+d.numDeliver+'">';
                        }else {
                            return '<span>'+d.numDeliver+'</span>';
                        }
                    }
            }
                //,{title: '<span style="color: red;">*</span>'+' 所属公司简称', field:'vGsJc', align:"center",width:100}
                //,{title: '<span style="color: red;">*</span>'+' 所属公司编码', field:'vGsBm', align:"center",width:100}
                ,{title: '操作',  align:"center",width:100,templet:
                    function(d){
                        return '<button class="layui-btn layui-btn-xs" style="background-color: '+(enableEdit== 1 ?'#FF5722':'#E2E2E2')+';" onclick="delRow(\''+d.rowId+'\')">  删除  </button>';
                    }
            }
            ]
        ],
        //数据渲染完毕的回调函数
        done: function(res){
            //console.log('detailList222',detailList);
            //detailList = table.cache.dhtable;//每次重载都赋值更新表缓存
            //layui.table.reload('dhtable', {data:detailList});
            //合并单元格
            /**
             * 参数1  需要合并列的数组，0代表的是合并单选按钮或者是复选框 radio/checkbox 后端需要将这些字段进行排序
             * 参数2  当前表格的index (用于在一个页面中有使用了多个表格的情况，如果只有一个表格填0就行
             * 		  index这个值是表格加载的顺序，从0开始，如果页面上表格很多建议debug用 $(".layui-table-body")[index]看一下就拿到了)
             * 参数3  是按照html元素合并，还是按照标签中的text内容合并，建议填true
             * 参数4  radio/checkbox根据哪一行去合并
             */
            layuiRowspan([ 'commodityCode', 'name', 'numBox', 'numSingleBox', 'numCommodity', 'volume', 'weight', 'productNameCn', 'productMaterialCn', 'productCodeHs'], "0", true, "commodityCode");

        },
        error: function(res, msg){
            console.log(res, msg)
        }
    });
    //layui.table.reload('dhtable', {data:detailList});
    //保存按钮封装的点击事件赋空
    $(function(){
        $('.tp-save').attr('onclick','');
        $('.tp-save').attr('lay-filter','btn-edit');
        $('.tp-save').attr('lay-submit',true);
    })

    // 保存操作
    form.on('submit(btn-edit)', function(data){

        //表头非空判断
        var is_return = 0,//是否中断保存
            judge_fields=k_fields.concat(t_fields),//判断必填字段：静态表格(表头加静态网格字段)
            must_field={},//表头必填且不隐藏字段
            inputForm = $(".head-form");//单据表头表单
        $.each(judge_fields,function (fk,fv) {
            if(fv.fieldFrontRequired)must_field[fv.fields] = fv.fieldName + " 不能为空";//遍历必填且不隐藏的字段
        });
        $.each(must_field,function (k,v) {
            if(!inputForm.find("[name='"+k+"']").val()){
                $.modal.msgError(v);
                is_return = 1;
                if(!typeof table=='undefined')inputForm.find("#"+k).css('border','1px solid red');
                inputForm.find("#"+k).focus();
                return false;
            }
        });
        if(is_return)return false;

        //明细非空判断
        if(detailList!=null && detailList.length>0){
            var error = null;
            for(var i=0;i<detailList.length;i++){
                var info = detailList[i];
                if(isNull(info.commodityCode) )error =  '商品：'+info.name+'- 商品编码 不能为空';
                if(isNull(info.name) )error =  '商品：'+info.name+'- 商品名称 不能为空';
                if(isNull(info.numBox) )error =  '商品：'+info.name+'- 箱数 不能为空';
                if(parseInt(info.numBox)<=0 )error =  '商品：'+info.name+'- 箱数 应该大于0';
                if(isNull(info.numSingleBox) )error =  '商品：'+info.name+'- 单箱数量 不能为空';
                if(isNull(info.numCommodity) )error =  '商品：'+info.name+'- 商品数量 不能为空';
                if(isNull(info.volume) )error =  '商品：'+info.name+'- 箱规(cm) 不能为空';
                if(isNull(info.weight) )error =  '商品：'+info.name+'- 箱重(kg) 不能为空';
                if(isNull(info.codeStockOn) )error =  '商品：'+info.name+'- 所在仓库 不能为空';
                if(isNull(info.codeStockLocation) )error =  '商品：'+info.name+'- 货位编码 不能为空';
                if(isNull(info.codeStockArea) )error =  '商品：'+info.name+'- 库区 不能为空';
                if(isNull(info.numAvailable) )error =  '商品：'+info.name+'- 可用数量 不能为空';
                if(isNull(info.numDeliver) )error =  '商品：'+info.name+'- 发货数量 不能为空';
                if(parseInt(info.numDeliver)<=0 )error =  '商品：'+info.name+'- 发货数量 应该大于0';
                if(isNull(info.productNameCn) )error =  '商品：'+info.name+'- 商品品名 不能为空';
                if(isNull(info.productMaterialCn) )error =  '商品：'+info.name+'- 商品材质 不能为空';
                if(isNull(info.productCodeHs) )error =  '商品：'+info.name+'- 海关编码 不能为空';
                //if(isNull(info.vGsJc) )error =  '商品：'+info.name+'- 所属公司简称 不能为空';
                //if(isNull(info.vGsBm) )error =  '商品：'+info.name+'- 所属公司编码 不能为空';
            }
            if(error!=null){
                layer.msg('部分单据明细未填写完整：'+error);
                return ;
            }
            var isBiger = null;
            for(var i=0;i<detailList.length;i++){
                var info = detailList[i];
                if(parseInt(info.numDeliver)-parseInt(info.numAvailable)>0)isBiger = '商品：'+info.name+'的发货数量不能大于可用数量';
                if(info.codeStockOn!=$('#warehouseAddress').val())isBiger = '商品：'+info.name+'的所在仓库应该与上面所选择的所在地仓库一致';
            }
            if(isBiger!=null){
                layer.msg(isBiger);
                return ;
            }
            //查询发货数量是否等于总计
            var isBigerAll = null;
            for(var i=0;i<detailList.length;i++){
                var info = detailList[i];
                var infoNumCommodity = detailList[i].numCommodity;
                var count = 0;
                for(var j=0;j<detailList.length;j++){
                    if(detailList[j].gaugeMaintenanceId == detailList[i].gaugeMaintenanceId){
                        count = parseInt(count) + parseInt(detailList[j].numDeliver);
                    }
                }
                if(parseInt(count)-parseInt(infoNumCommodity)!=0)isBigerAll = '商品：'+info.name+'的发货数量之和必须等于商品数量：'+detailList[i].numCommodity;
            }
            if(isBigerAll!=null){
                layer.msg(isBigerAll);
                return ;
            }
        }else {
            layer.msg('单据明细 不能为空');
            return ;
        }

        //保存
        $.operate.post("/storage/deliveryRequest/editpost",{'infoMap':JSON.stringify(data.field),nid:$('#nid').val(),infoItems:JSON.stringify(detailList)},function(res){
            $.modal.closeLoading();
            //console.log('res111',res);
            layer.msg(res.msg);
            if(res.code == 0){
                setTimeout(function () {
                    window.location.href = '/storage/deliveryRequest/edit?nid=' + res.data ;
                    setTimeout(function () {layui.table.reload('dhtable', {data:detailList});}, 1000);
                }, 1000);
            }
        })


    })
});

function isNull(str) {
    var res = false;
    if(str==undefined || str==null || str==''){
        res = true;
    }
    return res;
}

//箱数输入框变更
function numberInput1(gaugeMaintenanceId,obj) {
    for(var i=0;i<detailList.length;i++){
        if(detailList[i].gaugeMaintenanceId==gaugeMaintenanceId){
            detailList[i].numBox = obj.value;
            detailList[i].numCommodity = parseInt(obj.value)*parseInt( detailList[i].numSingleBox);
        }
    }
    layui.table.reload('dhtable', {data:detailList});

}

//箱数输入框变更
function numberInput(rowId,obj) {
    detailList[rowId].numBox = obj.value;
    layui.table.reload('dhtable', {data:detailList});
}

//发货数量输入框变更
function numDeliverInput(rowId,obj) {
    //var gaugeMaintenanceId = detailList[parseInt(rowId)].gaugeMaintenanceId;
    detailList[rowId].numDeliver = obj.value;
    /*
    var numCommodity = 0;
    for(var i=0;i<detailList.length;i++){
        if(detailList[i].gaugeMaintenanceId==gaugeMaintenanceId){
            if(detailList[i].numDeliver!=null && detailList[i].numDeliver!=''){
                numCommodity = parseInt(numCommodity) + parseInt(detailList[i].numDeliver);
            }
        }
    }
    for(var i=0;i<detailList.length;i++){
        if(detailList[i].gaugeMaintenanceId==gaugeMaintenanceId){
            detailList[i].numCommodity = numCommodity;
        }
    }
     */
    layui.table.reload('dhtable', {data:detailList});
}

//新增按钮
function  addDetail() {

    var inputWarehouseAddress = $('#warehouseAddress').val();
    if (inputWarehouseAddress == null || inputWarehouseAddress == '') {
        layer.msg('请先选择所在仓库！');
        return;
    }
    var inputDestHouseAddress = $('#destHouseAddress').val();
    if (inputDestHouseAddress == null || inputDestHouseAddress == '') {
        layer.msg('请先选择目的地仓库！');
        return;
    }
    var inputvGsJc = $('#vGsJc').val();
    if (inputvGsJc == null || inputvGsJc == '') {
        layer.msg('请先选择公司！');
        return;
    }
    layer.open({
        type: 2,
        area: [($(window).width() - 200) + 'px', ($(window).height() - 100) + 'px'],
        fix: false,//不固定
        offset: '10%',//距离顶部
        maxmin: true,//最大最小化
        shade: 0.3,//遮罩
        title: '箱规维护列表',
        content: "/storage/deliveryRequest/select2?pagetype=checkbox&by=direct&fmoduleTable=" + moduleTable + "&selectedObject=" + inputDestHouseAddress,
        btn: ['确定', '取消'],
        shadeClose: true,// 弹层外区域关闭
        yes: function (index, layero) {
            var res = window["layui-layer-iframe" + index].callbackdata();
            console.log("res", res);
            if(res!=null && res.length>0){
                for(var j=0;j<res.length;j++){
                    resetDetailListByAdd(res[j]);
                }
            }
            layer.close(index);
            layui.table.reload('dhtable', {data:detailList});

        }
    });
}

//查询货位编码
function getCodeStockLocation(rowId){
    if(enableEdit!=1)return;
    var inputWarehouseAddress = $('#warehouseAddress').val();
    if (inputWarehouseAddress == null || inputWarehouseAddress == '') {
        layer.msg('请先选择所在仓库！');
        return;
    }
    var inputDestHouseAddress = $('#destHouseAddress').val();
    if (inputDestHouseAddress == null || inputDestHouseAddress == '') {
        layer.msg('请先选择目的地仓库！');
        return;
    }
    var inputvGsJc = $('#vGsJc').val();
    if (inputvGsJc == null || inputvGsJc == '') {
        layer.msg('请先选择公司！');
        return;
    }
    var commodityCode = detailList[rowId].commodityCode;
    var gaugeMaintenanceId = detailList[rowId].gaugeMaintenanceId;
    var noChooseList = "";
    for(var i=0;i<detailList.length;i++){
        if(gaugeMaintenanceId==detailList[i].gaugeMaintenanceId){
            if(detailList[i].guidKc!=undefined && detailList[i].guidKc!=null && detailList[i].guidKc!=''){
                if(noChooseList == ""){
                    noChooseList =detailList[i].guidKc;
                }else {
                    noChooseList = noChooseList + ','+detailList[i].guidKc;
                }
            }
        }
    }


    layer.open({
        type: 2,
        area: [($(window).width() - 200) + 'px', ($(window).height() - 100) + 'px'],
        fix: false,//不固定
        offset: '10%',//距离顶部
        maxmin: true,//最大最小化
        shade: 0.3,//遮罩
        title: '选择货位编码',
        content: "/storage/deliveryRequest/getCodeStockLocation?deleted=0&pagetype=radio&by=direct&fmoduleTable=" + moduleTable
            + "&productcode=" + commodityCode  + "&warehouseAddress=" + $('#warehouseAddress').val()+ "&vGsBm=" + $('#vGsBm').val() + "&noChooseList="+noChooseList,
        btn: ['确定', '取消'],
        shadeClose: true,// 弹层外区域关闭
        yes: function (index, layero) {
            var res = window["layui-layer-iframe" + index].callbackdata();
            console.log("res", res);
            if(res!=undefined && res!=null && res!="none"){
                detailList[rowId].scGuid = res.guidKc;//guid
                detailList[rowId].rkGuid = res.rkGuid;//入库id
                detailList[rowId].vGsBm = res.vGsBm;//所属公司编码
                detailList[rowId].vHw = res.vHw;//货位编码
                detailList[rowId].vKq = res.vKq;//库区
                detailList[rowId].gDepot = res.gDepot;//所在仓库
                detailList[rowId].productcode = res.productcode;
                detailList[rowId].codeStockLocation = res.vHw;//货位编码
                detailList[rowId].codeStockArea = res.vKq;//库区
                detailList[rowId].numAvailable = res.productNum;//可用数量
                detailList[rowId].vGsJc = res.vGsJc;//所属公司简称
                detailList[rowId].guidKc = res.guidKc;//库存id
            }
            layer.close(index);
            layui.table.reload('dhtable', {data:detailList});

        }
    });
}

//删除按钮
function delRow(rowId) {
    if(enableEdit!=1)return;
    var newList = [];
    for(var i=0;i<detailList.length;i++){
        if(detailList[i].rowId!=rowId){
            newList.push(detailList[i]);
        }
    }
    detailList = newList;
    setRowId();
    layui.table.reload('dhtable', {data:detailList});
}

//行内新增
function addRowIn(gaugeMaintenanceId){
    if(enableEdit!=1)return;
    var newList = [];
    var isAddNew = false;
    var sameInfo = {};
    var hasSame = false;
    for(var i=0;i<detailList.length;i++){
        if(detailList[i].gaugeMaintenanceId==gaugeMaintenanceId){
            hasSame = true;
            sameInfo = detailList[i];
        }
        if(hasSame == true && detailList[i].gaugeMaintenanceId!=gaugeMaintenanceId && !isAddNew){
            isAddNew = true;
            var info = setDetailInfoByIn(sameInfo);
            newList.push(info);
        }
        newList.push(detailList[i]);
    }
    if(!isAddNew){
        var info = setDetailInfoByIn(sameInfo);
        newList.push(info);
    }
    detailList = newList;
    setRowId();
    layui.table.reload('dhtable', {data:detailList});
}

//整行新增
function resetDetailListByAdd(addList) {
    var newAdd = setDetailInfo(addList);
    if(detailList==null || detailList==[] || !detailList.length>0){
        detailList = [];
        detailList.push(newAdd);
    }else {
        var newList = [];
        var isAddNew = false;
        var numCommodity = '';
        var numBox = '';
        var hasSame = false;
        for(var i=0;i<detailList.length;i++){

            if(detailList[i].gaugeMaintenanceId==newAdd.gaugeMaintenanceId){
                hasSame = true;
                numCommodity = detailList[i].numCommodity;
                numBox = detailList[i].numBox;
            }
            if(hasSame == true && detailList[i].gaugeMaintenanceId!=newAdd.gaugeMaintenanceId && !isAddNew){
                isAddNew = true;
                newAdd.numCommodity = numCommodity;
                newAdd.numBox = numBox;
                newList.push(newAdd);
            }
            newList.push(detailList[i]);
        }
        if(!isAddNew){
            newAdd.numCommodity = numCommodity;
            newAdd.numBox = numBox;
            newList.push(newAdd);
        }
        detailList = newList;
    }
    setRowId();
}

//设置唯一标识
function setRowId() {
    //console.log(detailList);
    if(detailList!=null && detailList.length>0){
        for(var i=0;i<detailList.length;i++){
            detailList[i].rowId = i;
            //detailList[i].id = i;
        }
    }
}

function setDetailInfoByIn(sameInfo) {
    var info = {};
    info.gaugeMaintenanceId = sameInfo.gaugeMaintenanceId;
    info.commodityCode=sameInfo.commodityCode;
    info.name=sameInfo.name;
    info.numBox=sameInfo.numBox;
    info.numSingleBox=sameInfo.numSingleBox;
    info.numCommodity=sameInfo.numCommodity;
    info.volume=sameInfo.volume;
    info.weight=sameInfo.weight;
    info.height=sameInfo.height;
    info.length=sameInfo.length;
    info.width=sameInfo.width;
    //info.guid="";
    if(info.codeStockOn==undefined || info.codeStockOn==null)info.codeStockOn = $('#warehouseAddress').val();
    if(info.codeStockLocation==undefined || info.codeStockLocation==null)info.codeStockLocation = "";
    if(info.codeStockArea==undefined || info.codeStockArea==null)info.codeStockArea = "";
    if(info.numAvailable==undefined || info.numAvailable==null)info.numAvailable = "";
    if(info.numDeliver==undefined || info.numDeliver==null)info.numDeliver = "";
    if(info.vGsJc==undefined || info.vGsJc==null)info.vGsJc = "";
    if(info.vGsBm==undefined || info.vGsBm==null)info.vGsBm = "";
    info.productNameCn=sameInfo.productNameCn;
    info.productMaterialCn=sameInfo.productMaterialCn;
    info.productCodeHs=sameInfo.productCodeHs;
    return info;
}

function setDetailInfo(info) {
    if(info.gaugeMaintenanceId==undefined || info.gaugeMaintenanceId==null)info.gaugeMaintenanceId = info.gaugeMaintenanceId;
    if(info.commodityCode==undefined || info.commodityCode==null)info.commodityCode = info.commodityCode;
    if(info.numSingleBox==undefined || info.numSingleBox==null)info.numSingleBox = info.numSingleBox;
    if(info.volume==undefined || info.volume==null)info.volume = info.length+'*'+info.width+'*'+info.height;
    if(info.codeStockOn==undefined || info.codeStockOn==null)info.codeStockOn = $('#warehouseAddress').val();
    if(info.codeStockLocation==undefined || info.codeStockLocation==null)info.codeStockLocation = "";
    if(info.codeStockArea==undefined || info.codeStockArea==null)info.codeStockArea = "";
    if(info.numAvailable==undefined || info.numAvailable==null)info.numAvailable = "";
    if(info.numDeliver==undefined || info.numDeliver==null)info.numDeliver = "";
    if(info.vGsJc==undefined || info.vGsJc==null)info.vGsJc = "";
    if(info.vGsBm==undefined || info.vGsBm==null)info.vGsBm = "";
    if(info.productNameCn==undefined || info.productNameCn==null)info.productNameCn = "";
    if(info.productMaterialCn==undefined || info.productMaterialCn==null)info.productMaterialCn = "";
    if(info.productCodeHs==undefined || info.productCodeHs==null)info.productCodeHs = "";
    //info.guid="";
    return info;
}